
import json
# 导入数据请求模块
import requests
# 导入csv模块
import csv
# 导入哈希模块
import hashlib
# 导入时间模块
import time
# 导入编码的方法
from urllib.parse import quote

def GetW(wts, NextPage):
    # 进行编码处理
    pagination_str = quote(NextPage)
    """w_rid加密参数"""
    l = [
        "mode=2",
        "oid=710125501",
        f"pagination_str={pagination_str}",
        "plat=1",
        "type=1",
        "web_location=1315875",
        f"wts={wts}"
    ]
    y = '&'.join(l)
    string = y + "ea1db124af3c7062474693fa704f4ff8"
    MD5 = hashlib.md5()
    MD5.update(string.encode('utf-8'))
    w_rid = MD5.hexdigest()
    print(w_rid)
    return w_rid
def GetContent(offset,num):
    d=[]
    """发送请求"""
    # 模拟浏览器
    headers = {
        # user-agent 用户代理, 表示浏览器基本身份信息
        "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
    }
    # 请求网址
    url = 'https://api.bilibili.com/x/v2/reply/wbi/main'
    pagination_str = '{"offset": %s}'% offset
    # 获取当前时间戳
    wts = int(time.time())
    # 获取加密参数
    w_rid = GetW(wts=wts, NextPage=pagination_str)
    # 查询参数
    data = {
        'oid': '710125501',
        'type': '1',
        'mode': '2',
        'pagination_str': pagination_str,
        'plat': '1',
        'web_location': '1315875',
        'w_rid': w_rid,
        'wts': wts,
    }
    # 发送请求
    response = requests.get(url=url, params=data, headers=headers)
    """获取数据"""
    # 获取响应的json数据
    json_data = response.json()
    """解析数据"""
    # 字典取值, 提取评论信息所在replies列表
    replies = json_data['data']['replies']
    # for循环遍历, 提取列表里面元素
    for index in replies:
        # 提取具体评论数据内容
        dit = {
            '性别': index['member']['sex'],
            '评论': index['content']['message'],
            '点赞数':index['like'],
            '评论时间':index['ctime'],
            '用户id':index['rpid'],
            '回复量':index['rcount']
        }
        """保存数据"""
        print(dit)
        csv_writer.writerow(dit)
    # 获取下一页请求参数
    NextPage = json_data['data']['cursor']['pagination_reply']['next_offset']
    next_offset = json.dumps(NextPage)
    return next_offset

if __name__ == '__main__':
    # 创建csv文件
    f = open(file='哪吒.csv', mode='a', encoding='utf-8-sig', newline='')
    # 字典写入方法
    csv_writer = csv.DictWriter(f, fieldnames=['用户id', '性别', '评论时间','点赞数','评论','回复量'])
    # 写入表头
    csv_writer.writeheader()
    offset = '""'
    for page in range(1, 1000):
        try:
            offset = GetContent(offset=offset, num=page)
        except Exception as e:
            pass
